<template>
  <a-spin :spinning="loading">
    <a-card size="small" >
      <div>
        <div v-show="!disabled" class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 总分不得高于<a style="font-weight: 600">{{maxScore}}</a>分;
          <i class="anticon anticon-info-circle ant-error-icon"></i> 目前总积分: <a :style="computeColor"> {{totalScore}} </a>
          <a-button  type="danger" size="small" style="float:right" @click="save" v-has="'user:education-service-operate'"> 保存 </a-button>
        </div>

        <a-row type="flex" style="margin-bottom:10px" :gutter="16" >
          <a-col :span="2">时间</a-col>
          <a-col :span="6">教师姓名</a-col>
          <a-col :span="10">工作内容</a-col>
          <a-col :span="3">积分</a-col>
          <a-col v-show="!disabled" :span="2" v-has="'user:education-service-operate'">删除</a-col>
        </a-row>

        <a-row type="flex" v-for="(item, index) in dataSource" :key="index" :gutter="16">
          <a-form-model :ref="getRef(index)" style="width: 100%" :model="dataSource[index]" :rules="rules">
            <a-form-model-item style="display: none">
              <a-input placeholder="id" v-model="item.id" />
            </a-form-model-item>
            <a-col :span="2">
              <a-form-model-item class="gfxy-item" prop="date">
                <a-input placeholder="时间" v-model="item.date" :disabled="true"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item class="gfxy-item" prop="workNo">
                <j-select-user-by-dep  v-model="item.workNo"  :multi="false" :disabled="true"></j-select-user-by-dep>
              </a-form-model-item>
            </a-col>

            <a-col :span="10">
              <a-form-model-item class="gfxy-item" prop="projectName">
                <a-input placeholder="工作内容" v-model="item.projectName" :disabled="disabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="3">
              <a-form-model-item class="gfxy-item" prop="score">
                <a-input-number :min="0" placeholder="积分" v-model="item.score" :disabled="disabled"/>
              </a-form-model-item>
            </a-col>
            <a-col v-show="!disabled" :span="2">
              <a-form-model-item class="gfxy-item">
                <a-popconfirm title="确定删除该数据？" @confirm="delRow(index)" okText="确定" cancelText="取消" :disabled="disabled">
                  <a-icon type="minus-circle" style="fontSize :20px;color: #faad14"/>
                </a-popconfirm>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
        <a-button v-show="!disabled" type="dashed" style="width: 100%;margin-top: 10px;margin-bottom: 10px" @click="addItem" :disabled="disabled" v-has="'user:education-service-operate'">
          <a-icon type="plus" /> 添加工作项
        </a-button>
      </div>
    </a-card>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@api/manage'


export default {
  name: 'EducationAndServiceItems',
  props: ['teacherInfo','disabled'],
  data(){
    return {
      loading:false,
      dataSource:[],
      maxScore: 25,
      queryParam:{
        workNo:'',
        orgCode:'',
      },
      rules: {
        date: [{required: true,message: '时间不能为空',trigger: 'blur'}],
        workNo: [{required: true,message: '教师不能为空',trigger: 'blur'}],
        projectName: [{required:true, message:'请填写工作内容',trigger: 'blur'}],
        score:[{required:true, message:'请输入积分', trigger: 'blur'}]
      } ,
      url: {
        list: "/educationandservice/educationAndService/list",
        save: '/educationandservice/educationAndService/save'
      }
    }
  },
  computed: {
    computeColor: function(){
      let color = this.totalScore > this.maxScore ? 'red' : '#1890FF';
      return {
        color: color,
        fontWeight: 600
      };
    },
    totalScore: function(){
      let result = 0;
      this.dataSource.forEach(item=>{
        result = result + item.score;
      })
      return result;
    }
  },
  watch: {
    teacherInfo: {
      immediate: true,
      handler(obj) {
        console.log(obj);
        this.dataSource = [];
        this.loadData();
      }
    },
  },

  methods: {
    loadData(){
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }

      var params = { workNo:this.workNo,orgCode:this.orgCode,date:this.date };//查询条件
      console.log(params);
      console.log(this.teacherInfo)
      this.loading = true;
      console.log(this.url.list,"adjflakjsdflkasjdfklsjdfkljs")
      getAction(this.url.list, this.teacherInfo).then((res) => {
        console.log(res);
        if (res.success) {
          this.dataSource = res.result.records||res.result;

        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    getRef(index){
      return 'formref_' + index
    },
    addItem(){
      console.log(this.teacherInfo)
      let newItem = Object.assign({score:0},this.teacherInfo);
      this.dataSource.push(newItem)
    },
    delRow(index){
      this.dataSource.splice(index,1);
    },
    save(){

      new Promise((resolve,reject) => {
        console.log("开始校验工作项")
        this.validateList()? resolve(): reject("请检查工作项列表");
      }).then(()=>{
        new Promise((resolve,reject)=>{
          console.log("开始校验总积分")
          this.totalScore <= this.maxScore ? resolve(): reject("总积分超过" + this.maxScore+"分");
        }).then(()=>{
          const that = this;
          that.confirmLoading = true;
          let param = Object.assign({},that.teacherInfo);
          param.items = that.dataSource
          let r = this.validateList();

          httpAction(that.url.save,param,'put').then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.loadData();
          })
        }).catch((msg)=>{
          this.$message.error(msg);
          return false;
        })
      }).catch((msg)=>{
        this.$message.error(msg)
        return false;
      })



      // // 触发表单验证
      // this.$refs.form.validate(valid => {
      //   console.log(valid)
      //   if (valid) {
      //
      //   }
      //
      // })
    },
    validateList() {

      let result = true;
      for (let key in this.$refs) {

        if(this.$refs[key].length !=0 && typeof this.$refs[key][0].validate === 'function'){
          this.$refs[key][0].validate(valid => {
            result = result && valid;
            return;
          })
        }
      }
      return result;
    }
  },
  mounted() {

  }
}
</script>

<style scoped>
.gfxy-item{
  margin-top:5px;
}
.ant-row {
  margin-bottom: 0;
}
</style>